<template>
  <!-- 注册弹框 -->
  <el-dialog :visible.sync="isShow" width="600px" class="register">
    <!-- 自行更改弹窗标题 -->
    <div slot="title" class="title">用户注册</div>
    <el-form class="form" :model="form" :rules="rules" label-width="70px" ref="form"> 
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="baseUrl+'/'+form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" >
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" offset="1">
            <img class="img-yzm"  @click="changeCode" :src="CodeSrc" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode" ></el-input>
          </el-col>
          <el-col :span="8" offset="1">
            <el-button  @click="getPhoneCode" :disabled="totalTime !=5">获取用户验证码<span v-if="totalTime!=5">({{totalTime}}s)</span></el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item class="anniujuzhong">
        <el-button @click="isShow=false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
// 导入
import{getPhoneCodeApi,registerUserApi} from '@/api/register.js'
export default {
  // 侦听器
  watch:{
    "isShow"(newVal){
      if(newVal==false){
           //清空表单
           this.$refs.form.resetFields()
      }
    }
  },
  data() {
    return {
      // 基地址赋值
      baseUrl: process.env.VUE_APP_URL,
      //验证码点击
      CodeSrc:process.env.VUE_APP_URL+'/captcha?type=sendsms',
      //注册弹框开关
      isShow: false,
      //头像上传的CV对象不能删
      imageUrl: "",
      //验证码点击后时间
      totalTime:5,
      form: {
        avatar: "", //	是	string	头像地址
        username: "", //	是	string	用户名
        email: "", //	是	string	邮箱
        phone: "", //	是	string	手机号
        password: "", //	是	string	密码
        code: "", //	是	string 图形吗
        rcode:""  //图形验证码
      },
      rules: {
        avatar: [
          { required: true, message: "请输入头像", trigger: "blur" },
          
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "名输入邮箱", trigger: "blur" },
          { 
            validator:(rule,value,callback)=>{
              
               let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
               if(reg.test(value)){
                 callback()
               }else{
                 callback(new Error("请正确输入邮箱地址"))
               }
            },trigger:'change'
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator:(rule,value,callback)=>{
                
               let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
               if(reg.test(value)){
                 callback()
               }else{
                 callback(new Error("请正确手机地址"))
               }
            },trigger:'change'
            }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        rcode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
         code:[
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ]
      },
    };
  },
  methods: {
    //头像上传代码
    handleAvatarSuccess(res) {
      //上传后获取到图片的地址
      this.form.avatar=res.data.file_path
      //上传成功后，由于该 组件内部没有执行它的表单验证，所以我们要人为触发
      //父传子（父调用子方法）1：在该子组件标签定义ref  
      this.$refs.form.validateField(['avatar'])
      
       
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //头像上传代码结束
    
    //确定按钮点击
    //表单全局验证
    submit(){
      this.$refs.form.validate(result=>{
        if(result){
          // this.$message.success('验证成功')
          registerUserApi(this.form).then(res=>{
            window.console.log(res)
            // if(res.data.code==200){
              this.$message.success('注册成功')
              this.isShow =false
            // }
          })
        }else{
          this.$message.error('验证失败')
        }
      })
    },
    //点击验证码图片 刷新验证码
    changeCode(){
      this.CodeSrc= process.env.VUE_APP_URL+'/captcha?type=sendsms&sahgsasd='+Date.now()
    },
    getPhoneCode(){
      //需要手机号和图形码都验证成功，需要调用el-form里的 局部验证validatefield方法
      //errorMessage=>{errorMessage错误信息，如果errorMessage=="表单验证失败"}
      //需求需要知道什么情况下验证通过
      let num=0
      //局部验证手机号和验证码
      this.$refs.form.validateField(['phone','code'],errorMessage=>{
        window.console.log(errorMessage)
        if(errorMessage==''){
          num++
        }
      })
      if(num==2){

        //倒计时功能
        //提前减一秒，避免中途这一秒钟内可以不停点
        this.totalTime--
        // 声明定时器
        let timeInterval = setInterval(()=>{
          // 变量数字--
          this.totalTime--
          if(this.totalTime==0){
            //删除定时器
            clearInterval(timeInterval)
            this.totalTime= 5
          }

        },1000)
        // this.$message.success('验证通过')
        //调用接口获取宪政吗 axios 1 装包 2.导入 3.使用
        //验证码接口地址错误

      getPhoneCodeApi({
           code:this.form.code, 
           phone:this.form.phone
      })
        .then(res=>{
          this.$message.success(res.data.data.captcha+'')
          window.console.log(res) 
        }).catch(error=>{
          window.console.log(error)
        })
      }else{
        this.$message.error('验证失败')
      }
      
    }
  },
};
</script>

<style lang="less">
.register {
  //    头部标题样式
  .title {
    height: 53px;
    line-height: 53px;
    color: #fff;
    background: linear-gradient(to right, #02c4fa, #1394fa);
    text-align: center;
  }
  .el-dialog__header {
    padding: 0px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader {
    text-align: center;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .img-yzm {
    width: 100%;
    height: 40px;
  }
  .anniujuzhong {
    text-align: center;
  }
}
</style>